import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.header import Header
from email.utils import formataddr

smtp_server = 'smtp.163.com'
smtp_port = 465
sender_email = 'kkw2004@163.com'
sender_password = 'KRSAYCWDZSCBYTDR'
recipient_email = '30107372@qq.com'

def send_email(titlestr,mailtext,imglist):
    # 创建一个 MIMEMultipart 邮件对象，邮件类型为 'related'
    message = MIMEMultipart('related')
    message['From'] = formataddr(("CryptoWaifu", sender_email))
    message['To'] = formataddr(("尊敬的主人", recipient_email))
    message['Subject'] = Header(titlestr,'utf-8')

    imgIndex = 1
    imgresult = ""
    for img in imglist:
        imghtml = '<img src="cid:image' + str(imgIndex)+ '">'
        # 打开并读入图片
        imgpath = './reportImage/' + img
        with open(imgpath, 'rb') as f:
            img_data = f.read()
            image = MIMEImage(img_data)
            image.add_header('Content-ID', '<image' + str(imgIndex) + '>')  # cid 名称需与html一致
            message.attach(image)
        imgresult += imghtml
        imgIndex += 1

    html = """
    <html>
      <body>
        <p>""" + mailtext + """</p>
        """+ imgresult +"""
      </body>
    </html>
    """

    body = MIMEText(html, 'html', 'utf-8')
    message.attach(body)

    try:
        smtp_connection = smtplib.SMTP_SSL(smtp_server, smtp_port)
        smtp_connection.login(sender_email, sender_password)
        smtp_connection.sendmail(sender_email, [recipient_email], message.as_string())
        smtp_connection.quit()
        print("邮件发送成功")
    except Exception as e:
        print("邮件发送失败:", e)

if __name__ == '__main__':
    send_email("测试邮件","这是一封测试用的邮件",['klineSample.png','macdSample.png','kdjSample.png'])
